package com.wkh.project.job.once;

import cn.hutool.core.collection.CollUtil;
import com.wkh.project.esdao.QuestionEsDao;
import com.wkh.project.model.dto.question.QuestionEsDTO;
import com.wkh.project.model.entity.Question;
import com.wkh.project.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * 全量同步题目到 es
 *
 * @author wangkehua
 */
// todo 取消注释开启任务
//@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) throws Exception {
        //1.从数据库查询所有题目数据
        List<Question> questionList = questionService.list();
        //1.1 判空
        if (CollUtil.isEmpty(questionList)){
            return;
        }
        //1.2 拿到题目总数
        int total = questionList.size();
        //2. 转换成Es实体
        List<QuestionEsDTO> questionEsDTOList = questionList.stream()
                .map(QuestionEsDTO::objToDto)
                .toList();
        //3.分批量插入Es
        int pageSize = 500;
        log.info("开始同步数据到ES，共{}条数据，每批{}条数据",total,pageSize);
        for(int i = 0; i<total; i+=pageSize){
            //3.1 同步数据的下标不能超过题目总数
            int end = Math.min(i + pageSize, total);
            log.info("开始同步数据，从 {} 到 {} ",i,end);
            //3.2 批量插入
            questionEsDao.saveAll(questionEsDTOList.subList(i,end));
            log.info("同步数据完成，从 {} 到 {} ",i,end);
        }
        log.info("同步数据完成，共{}条数据",total);
    }
}
